import axios from 'axios';
import { showToast, showLoadingToast } from 'vant';
import { useTokenStore } from '../stores/modules/user';
const tokenStore = useTokenStore();
const request = axios.create({
  baseURL: '/api',
  withCredentials: true,
  timeout: 10000
})
const isNeedShowToast = (config: any) => {
  if (config.url) {
    return !config.url?.includes('/interface/exams/histories')
  }
  return true
}
let loadingToast: any = null
// 请求拦截器
request.interceptors.request.use((config) => {
  // 如果是保存答案的接口则不用loading
  if (isNeedShowToast(config)) {
    loadingToast = showLoadingToast({
      message: '加载中...',
      forbidClick: true,
      loadingType: 'spinner',
    })
  }
  if (tokenStore.tokenData.access_token) {
    config.headers['Authorization'] = `Bearer ${tokenStore.tokenData.access_token}`
  }
  return config
})
// 响应拦截器
request.interceptors.response.use((response) => {
  if (loadingToast !== null) {
    loadingToast.close()
  }
  const { data, request } = response
  if (`${data.code}` !== '0' && !request.responseURL.includes('.json') && isNeedShowToast(response.config)) {
    showToast(data.message || '请求出错，请稍后重试')
  }
  return data
}, error => {
  if (loadingToast !== null) {
    loadingToast.close()
  }
  showToast(error.message)
  return Promise.reject(new Error(error.message))
})

export default request
